# api.py
# 封装接口请求相关操作
import requests
from config import API_BASE_URL, APP_ID, APP_SECRET

def get_token():
    """
    获取access_token
    :return: access_token字符串
    :raises Exception: 如果获取失败，抛出详细异常
    """
    url = f"{API_BASE_URL}/token/{APP_ID}/{APP_SECRET}"
    try:
        resp = requests.get(url, timeout=10)
        resp.raise_for_status()
        data = resp.json()
    except Exception as e:
        raise Exception(f"请求token接口异常: {e}")
    code = data.get("code")
    if code == 200:
        return data["access_token"]
    elif code == 5005:
        raise Exception(f"appid信息验证失败: {data.get('msg')}")
    else:
        raise Exception(f"获取token失败: code={code}, msg={data.get('msg')}, 返回内容: {data}")

def get_data(access_token, bmbh=None):
    """
    获取部门数据
    :param access_token: 认证token
    :param bmbh: 部门编号，可为空
    :return: data列表
    :raises Exception: 如果获取失败，抛出详细异常
    """
    url = f"{API_BASE_URL}/test/{access_token}"
    body = {}
    if bmbh:
        body["bmbh"] = bmbh
    try:
        resp = requests.post(url, json=body, timeout=10)
        resp.raise_for_status()
        data = resp.json()
    except Exception as e:
        raise Exception(f"请求数据接口异常: {e}")
    code = data.get("code")
    if code == 200:
        return data["data"]
    elif code == 5001:
        raise Exception(f"传入参数不合法: {data.get('msg')}")
    elif code == 5101:
        raise Exception(f"access_token相关错误: {data.get('msg')}")
    else:
        raise Exception(f"获取数据失败: code={code}, msg={data.get('msg')}, 返回内容: {data}") 